package com.sixbro.file.storage.service.impl;

import com.sixbro.file.storage.entity.FileDocument;
import com.sixbro.file.storage.service.FileService;
import com.sixbro.file.storage.util.FileUtils;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2022/1/16 14:14
 */
public abstract class AbstractFileStorageService implements FileService {

    @Override
    public FileDocument upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String filetype = FileUtils.getFiletype(originalFilename);
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + filetype;
        FileDocument document = FileDocument.builder()
                .originalFilename(originalFilename)
                .filename(filename)
                .filetype(filetype)
                .size(file.getSize())
                .contentType(file.getContentType())
                .build();
        uploadHandler(document, file);
        return document;
    }

    @Override
    public List<FileDocument> upload(List<MultipartFile> files) throws IOException {
        Assert.notNull(files);
        List<FileDocument> fileDocuments = new ArrayList<>();
        for (MultipartFile file : files) {
            FileDocument fileDocument = upload(file);
            fileDocuments.add(fileDocument);
        }
        return fileDocuments;
    }

    protected abstract void uploadHandler(FileDocument document, MultipartFile file) throws IOException;
}
